package com.atguigu.springboot.controller;

import com.atguigu.springboot.dao.DepartmentDao;
import com.atguigu.springboot.dao.EmployeeDao;
import com.atguigu.springboot.entities.Department;
import com.atguigu.springboot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * @author : leimingchao
 * @date Date : 2021年10月16日 12:41
 */
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;

    /**
     * 查询所有员工返回列表页面
     * @return
     */
    @GetMapping(value = "/emps")
    public String list(Model model) {
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("emps",employees);
        //放在请求域中
        //thymeleaf默认就会拼串
        //classpath:/templates/xxxx.html
        return "/emp/list";
    }

    @GetMapping(value = "/emp")
    public String toAddPage(Model model) {
        //来到添加页面,查询出所有的部门，在页面显示
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        return "emp/add";
    }

    //SpringMVC自动将请求参数和入参对象的属性进行一一绑定；要求请求参数的名字和javaBean入参的对象里面的属性名是一样的
    @PostMapping(value = "/emp")
    public String addEmployee(Employee employee) {
        //来到员工列表页面
        System.out.println("保存员工的信息：" + employee);
        //保存员工
        employeeDao.save(employee);
        //redirect:表示重定向到一个地址，/:代表当前项目路径
        //forward:表示转发到一个地址
        return "redirect:/emps";
    }

    @GetMapping(value = "/emp/{id}")
    public String toEditPage(@PathVariable(value = "id") Integer id,Model model) {
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp",employee);

        //来到添加页面,查询出所有的部门，在页面显示
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts",departments);
        //回到修改页面(add页面是一个修改添加二合一的页面)
        return "emp/add";
    }

    /**
     * 员工修改
     */
    @PutMapping(value = "emp")
    public String updateEmployee(Employee employee) {
        System.out.println("修改的员工数据：" + employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    /**
     * 员工删除
     * @param id
     * @return
     */
    @DeleteMapping(value = "/emp/{id}")
    public String deleteEmployee(@PathVariable(value = "id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
